<?php
namespace app\index\controller;
use app\common\controller\CommonController;
use think\Db;
class AdminController extends CommonController
{
    /******************************************** 登录写死 ******************************************/
    /**
     * 后台登录接口
     * @param string $password
     */
    public function login()
    {
        try {
            if($this->request->isPost()){
                $data = $this->request->post();
                if(empty($data['password']) || trim($data['password']) !== 'GKJ1_Z9lEG'){
                    echo json_encode(['code' => 1001,'msg' => 'fail','sub_msg' => 'invalid password']);    
                }
            }       
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

    /******************************************** 后台用户相关 ******************************************/

    /**
     * 用户列表接口
     * @param int $pagesize
     * @param int $page
     */
    public function userlist()
    {
        try {
            if($this->request->isPost()){
                $params = $this->request->post();
                $page     = isset($params['page']) && is_numeric($params['page']) ? (int)$params['page'] : 1;
                $pagesize = isset($params['pagesize']) && is_numeric($params['pagesize']) ? (int)$params['pagesize'] : 10;
                $start = ($page-1) * $pagesize;
                $res = Db::table('user')->order('id desc')->limit($start,$pagesize)->select();
                $count = Db::table('user')->count();
                foreach ($res as $key => $value) {
                    $num = Db::table('draw')->where(['uuid' => $value['uuid']])->count();
                    $res[$key]['drawnum'] = $num;
                    $res[$key]['prizenum'] = $num;
                }
                $data = [
                    'count'    => $count,
                    'pagecount'=> ceil($count/$pagesize),
                    'pagesize' => $pagesize,
                    'page'     => $page,
                    'data'     => $res
                ];
                echo json_encode(['code' => 1000,'msg' => 'success','data' => $data]);exit;     
            }    
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

    /******************************************** 后台奖品相关 ******************************************/

    /**
     * 奖品列表接口
     * 
     */
    public function prizelist()
    {
        try {
            if($this->request->isPost()){
                $date = Db::table('active_config')->field('date_start,date_end')->find();
                $res = Db::table('prize')->order('id asc')->select();
                echo json_encode(['code' => 1000,'msg' => 'success','data' => ['date' => $date,'list' => $res]]);exit;        
            }    
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

    /**
     * 修改活动时间
     * @param string $date_start
     * @param string $date_end
     */
    public function editDate()
    {
        try {
            if($this->request->isPost()){
                $date_pattern = "/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/";
                $params = $this->request->post();
                if(empty($params['date_start']) || !preg_match($date_pattern, $params['date_start']) || 
                empty($params['date_end']) || !preg_match($date_pattern, $params['date_end'])){
                    echo json_encode(['code' => 1001,'msg' => 'fail','sub_msg' => 'invalid date']);exit; 
                }
                if($params['date_start'] > $params['date_end']){
                    echo json_encode(['code' => 1001,'msg' => 'fail','sub_msg' => 'invalid date']);exit;    
                }
                $ret = Db::table('active_config')->where("1=1")->update(['date_start' => $params['date_start'],'date_end' => $params['date_end']]);
                if($ret !== false){
                    echo json_encode(['code' => 1000,'msg' => 'success','data' => []]);exit; 
                }
                echo json_encode(['code' => 1003,'msg' => 'fail','sub_msg' => 'edit the date fail']);exit;    
            }    
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }    
    }

    /******************************************** 中奖信息相关 ******************************************/

    /**
     * 中奖列表
     * @param string    $uuid
     * @param int       $prizeid
     * @param int       $isthing  
     */
    public function drawslist()
    {
        try {
            if($this->request->isPost()){
                $params = $this->request->post();
                $page     = isset($params['page']) && is_numeric($params['page']) ? (int)$params['page'] : 1;
                $pagesize = isset($params['pagesize']) && is_numeric($params['pagesize']) ? (int)$params['pagesize'] : 10;
                $start = ($page-1) * $pagesize;
                $field = "a.id draw_id,a.type,a.uuid,a.draw_date,a.prize_id,a.draw_info,b.name,b.isthing";
                $sql = "SELECT $field FROM draw a LEFT JOIN prize b ON a.prize_id = b.id WHERE 1=1 ";
                if(!empty($params['uuid'])){
                    $sql .= "AND a.uuid = '{$params['uuid']}' ";
                }
                if(!empty($params['prize_id'])){
                    $sql .= "AND a.prize_id = {$params['prize_id']} ";
                }
                if(!empty($params['isthing'])){
                    $sql .= "AND b.isthing = {$params['isthing']} ";
                }
                $order = "ORDER BY a.id DESC LIMIT {$start},{$pagesize}";
                $csql = str_replace($field,'count(*)',$sql);
                $sql .= $order;
                $res = Db::query($sql);
                $count = Db::query($csql)[0]['count(*)'];
                $data = [
                    'count'    => $count,
                    'pagecount'=> ceil($count/$pagesize),
                    'pagesize' => $pagesize,
                    'page'     => $page,
                    'data'     => $res
                ];
                echo json_encode(['code' => 1000,'msg' => 'success','data' => $data]);exit;
            }    
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }
    }

    /**
     * 导出中奖信息
     * @param string    $uuid
     * @param int       $prizeid
     * @param int       $isthing 
     */
    public function export()
    {
        try {
            if($this->request->isPost()){
                $sql = "SELECT * FROM draw a LEFT JOIN prize b ON a.prize_id = b.id WHERE 1=1 ";
                if(!empty($params['uuid'])){
                    $sql .= "AND a.uuid = '{$params['uuid']}' ";
                }
                if(!empty($params['prize_id'])){
                    $sql .= "AND a.prize_id = {$params['prize_id']} ";
                }
                if(!empty($params['isthing'])){
                    $sql .= "AND b.isthing = {$params['isthing']} ";
                }
                $order = "ORDER BY a.id DESC";
                $sql .= $order;
                $res = Db::query($sql);
                if(!$res){
                    echo json_encode(['code' => 1002,'msg' => 'fail','sub_msg' => '没有可下载数据']);exit;    
                }
                $excelTool = \app\tool\Export::getInstance();
                $excelTool->exportDraw($res);
            }
        } catch (\Exception $e) {
            echo json_encode(['code' => -1000,'msg' => 'system error','sub_msg' => $e->getMessage()]);
        }    
    }
}